from TVRageScraper import TVRageScraper
from NearestString import NearestString
from FilenameParser import parser1
import os

target = '/media/storage/video/series/Mythbusters/special'

class SeriesInfo(object):
  def __init__(self, episodes):
    self.episode_index = dict(    ((ep.series_number, ep.episode_number), ep) 
                         for  ep 
                         in   scraper.episodes
                         )

  def __call__(self, season, episode):
    return self.episode_index[(season,episode)]

def filename(ep_info):
  series   = ep_info.series_name
  season   = ep_info.series_number
  episode  = ep_info.episode_number
  title    = ''.join(    c
                     for  c 
                     in   ep_info.title.replace(' ','.').lower()
                     if   c.isalnum() or c == '.'
                     )
  return "%s.s%02de%02d.%s" % (series, season, episode, title)

def norm_str(string):
  return ''.join( c for c in string.lower() if c.isalnum() )

def extension(string):
  return string.split('.').pop()

if __name__ == "__main__":
  scraper = TVRageScraper("Mythbusters") 
  series = SeriesInfo(scraper.episodes)
  episode_numbers = dict(    (ep.title,(ep.series_number, ep.episode_number)) 
                      for  ep 
                      in   scraper.episodes
                      )
  parser = parser1()
  classifier = NearestString(episode_numbers.keys())

  for file in os.listdir(target):
    nn = classifier(file)
    result = parser(file)
    if result and (result['season'],result['episode']) != episode_numbers[nn]:
      print "Conflict for", file, "("+nn+")"
      file_norm = norm_str(file) 
      nn_norm = [ norm_str(s) for s in nn.split()]
      if all(n in file_norm for n in nn_norm):
        print "Accepted NN"
        season, episode = episode_numbers[nn]
      else:
        print "Accepted parse"
        season, episode = (result['season'],result['episode'])
    else:
      season, episode = episode_numbers[nn]
    try:
      newname = filename(series(season, episode))+'.'+extension(file)
    except KeyError: # Don't have info for the season/ep combo
      newname = file
    print " ",file,"--->",newname
    oldpath = os.path.join(target, file)
    newpath = os.path.join(target, newname)
    print "    rename  ",oldpath
    print "            ",newpath
    os.rename(oldpath, newpath)

